package com.statapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings.Secure;
import android.util.Log;

/** 
 * A BroadcastReceiver to react on incoming Android C2DM Messages
 * 
 * @author Peter Goldenbogen (Munich University of Applied Science)
 * @version 1.0 
 */

public class C2DMReceiver extends BroadcastReceiver {
	
	/**
	 * Called when the receiver gets started
	 * @param context The application context
	 * @param intent The related Intent
	 */
	@Override
	public void onReceive(Context context, Intent intent) {
		
		if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
			handleRegistration(context, intent);
		}

		else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
	        handleMessage(context, intent);
	     }
	}
	
	/**
	 * Handles received registration messages
	 * @param context The application context
	 * @param intent The related Intent
	 */
	private void handleRegistration(Context context, Intent intent) {
		
	    String registration = intent.getStringExtra("registration_id"); 
	    
	    if (intent.getStringExtra("error") != null) {
	        // Registration failed, should try again later.
	    } 
	    
	    else if (intent.getStringExtra("unregistered") != null) {
	        // unregistration done, new messages from the authorized sender will be rejected
	    } 
	    
	    else if (registration != null) {
	    	
			String action = intent.getAction();
			Log.d("C2DM", "Registration Receiver called");
			
			if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
				
				Log.d("C2DM", "Received registration ID");
				final String registrationId = intent.getStringExtra("registration_id");
				String error = intent.getStringExtra("error");
				if(error != null)
					Log.d("C2DM", "received error message: " + error);
				
				new Thread(new Runnable() {
					
					public void run() {
						sendRegistrationIdToServer(Secure.ANDROID_ID, registrationId);
					}
				}).start();

			}
	    }
	}
	
	/**
	 * Handles received content messages
	 * @param context The application context
	 * @param intent The related Intent
	 */
	private void handleMessage(Context context, Intent intent) {
		
		String action = intent.getAction();
		
		if ("com.google.android.c2dm.intent.RECEIVE".equals(action)) {
			
			Log.d("C2DM", "Received message");
			final String payload = intent.getStringExtra("payload");
			
			Intent sIntent = new Intent(context, NotificationService.class);
			sIntent.putExtra("payload", payload);
			context.startService(sIntent);
		}
	}
	
	/**
	 * Posts the C2DM ID to the data server via HTTP POST
	 * @param deviceId Id of the sending device
	 * @param registrationId received C2DM device token
	 */
	public void sendRegistrationIdToServer(String deviceId, String registrationId) {

		Log.d("C2DM", "Sending application ID to server");
		
		List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
		nameValuePairs.add(new BasicNameValuePair("deviceId", deviceId));
		nameValuePairs.add(new BasicNameValuePair("registrationId", registrationId));
		
		HttpClient client = new DefaultHttpClient();
		HttpPost post= new HttpPost("http://" + StatAppActivity.server_address + "/ChartService/rest/kpi/clientC2DM");
		Log.v("C2DM", "POST: " + "http://" + StatAppActivity.server_address + "/ChartService/rest/kpi/clientC2DM");
		
		try {
			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			HttpResponse response = client.execute(post);
			
			BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
			String line = "";
			
			while ((line = rd.readLine()) != null) {
				Log.v("HttpResponse", line);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
